package com.zhang.second.day07;

import com.zhang.second.utils.ClickEvent;
import com.zhang.second.utils.ClickSource;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.KeyedBroadcastProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @title: 查询流实现 - 广播流
 * @author: zhang
 * @date: 2022/2/2 17:17
 */
public class Example1_1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<ClickEvent> clickEventDataStreamSource = env
                .addSource(new ClickSource()).setParallelism(3);

        DataStreamSource<String> queryDS = env
                .socketTextStream("localhost", 9999);
        MapStateDescriptor<String, String> mapStateDescriptor = new MapStateDescriptor<>("map-state", Types.STRING, Types.STRING);
        BroadcastStream<String> broadcastStream = queryDS.broadcast(mapStateDescriptor);


        clickEventDataStreamSource.keyBy(r -> r.url)
                .connect(broadcastStream)
                .process(new KeyedBroadcastProcessFunction<String, ClickEvent, String, ClickEvent>() {
                    @Override
                    public void processElement(ClickEvent value, KeyedBroadcastProcessFunction<String, ClickEvent, String, ClickEvent>.ReadOnlyContext ctx, Collector<ClickEvent> out) throws Exception {
                        ReadOnlyBroadcastState<String, String> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
                        String query = broadcastState.get("query");
                        if (value.username.equals(query)) out.collect(value);
                    }

                    @Override
                    public void processBroadcastElement(String value, KeyedBroadcastProcessFunction<String, ClickEvent, String, ClickEvent>.Context ctx, Collector<ClickEvent> out) throws Exception {
                        BroadcastState<String, String> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
                        broadcastState.put("query",value);
                    }
                })
                .print();

        env.execute();
    }

}
